/**
 * 
 */
package com.csair.youth.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.mail.MessagingException;

import org.apache.commons.mail.EmailException;
import org.apache.log4j.Logger;

import com.csair.youth.constant.Constant;
import com.csair.youth.constant.ResourceConstant;
import com.csair.youth.dao.impl.hibernate3.CategoryDaoImpl;
import com.csair.youth.dao.impl.hibernate3.PermissionDaoImpl;
import com.csair.youth.dao.impl.hibernate3.ResourceDaoImpl;
import com.csair.youth.dao.impl.hibernate3.RoleDaoImpl;
import com.csair.youth.dao.impl.hibernate3.RolePermissionDaoImpl;
import com.csair.youth.dao.impl.hibernate3.SysConfigDaoImpl;
import com.csair.youth.dao.impl.hibernate3.UserDaoImpl;
import com.csair.youth.database.Category;
import com.csair.youth.database.Permission;
import com.csair.youth.database.Resource;
import com.csair.youth.database.RolePermission;
import com.csair.youth.database.SysConfig;
import com.csair.youth.database.User;

/**
 * @author mickey
 *	定时为非http上传的文件增加数据库resource记录，发送email给审核员
 */
public class ResourceGenerateJobServiceImpl {
	private static final Logger log = Logger.getLogger(ResourceGenerateJobServiceImpl.class);
	private static final SimpleDateFormat fullDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private ResourceDaoImpl rdao;
	private UserDaoImpl udao;
	private PermissionDaoImpl pdao;
	private RolePermissionDaoImpl rpdao;
	private RoleDaoImpl roledao;
	private SysConfigDaoImpl scdao;
	private CategoryDaoImpl cdao;
	
	private EmailServiceImpl emailService;
	
	public ResourceDaoImpl getRdao() {
		return rdao;
	}

	public void setRdao(ResourceDaoImpl rdao) {
		this.rdao = rdao;
	}

	public UserDaoImpl getUdao() {
		return udao;
	}

	public void setUdao(UserDaoImpl udao) {
		this.udao = udao;
	}

	public PermissionDaoImpl getPdao() {
		return pdao;
	}

	public void setPdao(PermissionDaoImpl pdao) {
		this.pdao = pdao;
	}

	public RolePermissionDaoImpl getRpdao() {
		return rpdao;
	}

	public void setRpdao(RolePermissionDaoImpl rpdao) {
		this.rpdao = rpdao;
	}

	public RoleDaoImpl getRoledao() {
		return roledao;
	}

	public void setRoledao(RoleDaoImpl roledao) {
		this.roledao = roledao;
	}

	public SysConfigDaoImpl getScdao() {
		return scdao;
	}

	public void setScdao(SysConfigDaoImpl scdao) {
		this.scdao = scdao;
	}
	
	public CategoryDaoImpl getCdao() {
		return cdao;
	}

	public void setCdao(CategoryDaoImpl cdao) {
		this.cdao = cdao;
	}

	public EmailServiceImpl getEmailService() {
		return emailService;
	}

	public void setEmailService(EmailServiceImpl emailService) {
		this.emailService = emailService;
	}

	public void scanAndGenerateResources(){
		log.warn("ftp上传文件自动扫描器于"+fullDateFormat.format(new Date())+"运行...");
		String scanPath = ResourceConstant.getInstance().getUploadTmpPath();
		File dir = new File(scanPath);
		String fileNames[] = dir.list();
		List<Resource> resourcesSaved = new ArrayList<Resource>();
		User autoUpload = udao.getUserByLoginName(Constant.USER_AUTO_UPLOAD_LOGIN_NAME);
		if(autoUpload == null){
			log.error("AUTO_UPLOAD_USER不存在，无法继续操作!");
			return;
		}
		if(fileNames != null){
			Category category = cdao.getCategoryByName(Constant.CATEGORY_FTP_AUTO_NAME);
			for(int i=0; i<fileNames.length; i++){
				if(rdao.getResourceByPath(scanPath+File.separator+fileNames[i]) == null){
					//没有resource记录，应该是使用ftp上传的文件，为其生成
					Resource result = autoSaveResourceRecord(new File(scanPath+File.separator+fileNames[i]), category, autoUpload);
					if(result != null){
						resourcesSaved.add(result);
					}
				}
			}
		}
		
		//email
		SysConfig config = scdao.getSysConfigByKey(Constant.SERVER_IP_PORT_KEY);
		String serverIpPort = null;
		if(config == null){
			serverIpPort = "http://127.0.0.1:8080/youth";
		}
		else{
			serverIpPort = config.getConfigValue();
		}
		String auditUrl = serverIpPort+(serverIpPort.endsWith("/")?"":"/")+"ResourceAudit.action";
		notifyAuditorsByEmail(resourcesSaved, auditUrl);
	}
	
	private Resource autoSaveResourceRecord(File file, Category category, User user){
		String path;
		try {
			path = file.getCanonicalPath();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("获取文件路径时发生错误!"+file.getName(), e);
			return null;
		}
		int indexOfLastSeparator = path.lastIndexOf(File.separator);
		if(path.endsWith(File.separator)){
			log.error("不正确的文件路径:"+path);
			return null;
		}
		String fileName = path.substring(indexOfLastSeparator+1);
		Resource res = new Resource();
		res.setFileName(fileName);
		res.setAbsolutePath(path);
		res.setContentType("application/octet-stream");
		res.setUploadUserId(user.getId());
		res.setUploadIp("local");
		res.setCategoryId(category.getId());
		
		long timestamp = file.lastModified();
		Date uploadTime = new Date();
		uploadTime.setTime(timestamp);
		res.setUploadTime(uploadTime);
		
		res.setAuditResult(Constant.RESOURCE_AUDIT_WAIT);
		
		res.setDownloadTimes(0);
		res.setLastModifyTime(new Date());
		res.setHttpDownAddress("");
		res.setFtpDownAddress("");
		rdao.save(res);
		
		return res;
	}
	
	private void notifyAuditorsByEmail(List<Resource> items, String auditUrl){
		if(items == null || items.size() == 0){
			log.error("没有新资源，将不发送邮件!");
			return;
		}
		Permission p = pdao.findFirstPermissionByURL(Constant.PERMISSION_AUDIT_EMAIL_URL);
		if(p != null){
			List rps = rpdao.findByPermissionId(p.getId());
			if(rps == null || rps.size() == 0){
				log.error("url为"+Constant.PERMISSION_AUDIT_EMAIL_URL+"的权限没有对应角色，将不发送email!");
				return;
			}
			else{
				String roleIds[] = new String[rps.size()];
				int count = 0;
				Iterator iter = rps.iterator();
				while(iter.hasNext()){
					RolePermission rp = (RolePermission)iter.next();
					roleIds[count++] = rp.getRoleId();
				}
				List users = udao.getUsersInRoles(roleIds);
				if(users == null || users.size() == 0){
					log.error("url为"+Constant.PERMISSION_AUDIT_EMAIL_URL+"的权限没有对应用户，将不发送email!");
				}
				else{
					//真正发送email了
					String title = "青年资源库有新资源待审核";
					for(int i=0; i<users.size(); i++){
						User u = (User)users.get(i);
						StringBuffer sb = new StringBuffer();
						sb.append("尊敬的"+u.getName()+",您好!\n  青年资源库扫描到有通过ftp上传的新资源待审核，请点击以下链接进行审核:\n");
						for(int j=0; j<items.size(); j++){
							sb.append("  "+(j+1)+". "+auditUrl+"?p="+items.get(j).getId()+"\n");
						}
						try {
							emailService.sendMail(u, title, sb.toString());
						} catch (EmailException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							log.error("发送邮件发生错误，user="+u.getEmail(), e);
						} catch (MessagingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							log.error("发送邮件发生错误，user="+u.getEmail(), e);
						}
					}
				}
			}
		}
		else{
			log.error("没有找到url为"+Constant.PERMISSION_AUDIT_EMAIL_URL+"的权限，将不发送email!");
			return;
		}
	}
}
